package com.riant.controller;

import com.riant.bean.ParamsException;
import com.riant.bean.User;
import com.riant.bean.response.BaseRes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;


/**
 * @Classname TestController
 * @Description TODO
 * @Date 2022/4/30 22:47
 * @Created by 张斌
 */

@Controller
public class TestController {
    private final Logger logger = LoggerFactory.getLogger(TestController.class);

    @RequestMapping(path = "/test", method = RequestMethod.GET)
    public String test() {
        return "success";
    }

    @RequestMapping(path = "/test1", method = RequestMethod.GET)
    public String test1(@RequestParam String name) {
        logger.info("name:{}", name);
        return "success";
    }

    @RequestMapping(path = "/test2/{name}/{id}", method = RequestMethod.GET)
    public String test2(@PathVariable("name") String name, @PathVariable("id") int id) {
        logger.info("name:{},id:{}", name, id);
        return "success";
    }

    @RequestMapping(path = "/test3", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    public String test3(@RequestBody User user) {
        logger.info("USER:{}", user.toString());
        return "success";
    }

    @RequestMapping(path = "/test4", method = RequestMethod.POST)
    @ResponseBody
    public String test4(@RequestBody User user) {
        logger.info("USER:{}", user.toString());
        return "success";
    }

    @RequestMapping(path = "/test5", method = RequestMethod.POST)
    @ResponseBody
    public BaseRes test5(@RequestBody User user) {
        logger.info("USER:{}", user.toString());

        return BaseRes.success();
    }

    @RequestMapping(path = "/test6", method = RequestMethod.POST)
    public ModelAndView test6(@RequestBody User user) {
        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/static/view/show.jsp");
        logger.info("USER:{}", user.toString());
        modelAndView.addObject(user);
        return modelAndView;
    }

    @RequestMapping(path = {"/test7"}, method = RequestMethod.POST)
    @ResponseBody
    public String test7(HttpEntity<User> httpEntity) {
        final User user = httpEntity.getBody();
        final HttpHeaders headers = httpEntity.getHeaders();
        headers.forEach((k, v) -> logger.info("key:{}，value:{}", k, v));
        logger.info("user:{}", user);
        //访问外部资源
        return "success";
    }

    @RequestMapping(path = {"/test8"}, produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    @ResponseBody
    public BaseRes test7(@Valid @RequestBody User user, BindingResult bindingResult) throws ParamsException {
        logger.info("user:{}", user);
        if (bindingResult.hasErrors()) {
            final StringBuilder stringBuilder = new StringBuilder();
            bindingResult.getAllErrors().forEach((item) -> stringBuilder.append(item.getDefaultMessage()).append(","));
            logger.warn("参数异常：{}", bindingResult.getFieldError().getDefaultMessage());
            throw new ParamsException("000001", stringBuilder.substring(0,stringBuilder.length()-1).toString());
        }
        return BaseRes.success();
    }

    @RequestMapping(path = {"/test9"}, method = RequestMethod.GET)
    @ResponseBody
    public String test9(@RequestParam String msg) throws ParamsException {
        if ("00".equals(msg)) {
            throw new ParamsException("000001", "参数异常处理");
        }
        //访问外部资源
        return "success";
    }
    @RequestMapping(path = {"/test10"}, method = RequestMethod.POST)
    @ResponseBody
    public BaseRes test10(HttpServletRequest request, HttpServletResponse response) throws ParamsException {
        final HttpSession session = request.getSession();//创建session，如果没有则创建
        session.setAttribute("name","lisi");
        session.setAttribute("passwrod","123456");
        final Cookie cookie = new Cookie("name","wangwu");
        response.addCookie(cookie);//向浏览器返回cookie
        logger.info("session信息：{},sessionID:{}",session.getAttributeNames(),session.getId());
        final BaseRes success = BaseRes.success();
        success.setData(session.getAttributeNames());
        return success;
    }

    @RequestMapping(path = {"/test11"}, method = RequestMethod.POST)
    @ResponseBody
    public BaseRes test11(HttpServletRequest request, HttpServletResponse response) throws ParamsException {
        final Cookie[] cookies = request.getCookies();
        String value= "default";
        for (Cookie cookie:cookies){
            if (cookie.getName().equals("name")){
                value=cookie.getValue();
            }
        }
        final Cookie cookie = new Cookie("name","wangwu");
        response.addCookie(cookie);//向浏览器返回cookie
        final BaseRes success = BaseRes.success();
        success.setData(value);
        return success;
    }

}
